<template>
    <div class="register-container">
      <h1>注册</h1>
      <form @submit.prevent="handleRegister">
        <div class="input-group">
          <label for="card">校园卡号:</label>
          <input type="text" id="card" v-model="user.card" required />
        </div>
        <div class="input-group">
          <label for="password">密码:</label>
          <input type="password" id="password" v-model="user.password" required />
        </div>
        <div class="input-group">
          <label for="confirm-password">确认密码:</label>
          <input type="password" id="confirm-password" v-model="user.confirmPassword" required />
        </div>
        <button type="submit">注册</button>
      </form>
    </div>
  </template>
  
  <script setup>
  import { ref } from 'vue';
  import axios from 'axios'; // 确保已经导入了axios 
  import { useRouter } from 'vue-router';
  
  const user = ref({
    card: '',
    password: '',
    confirmPassword: ''
  });

  const router = useRouter();
  
  const handleRegister = () => {
    if (user.value.password === user.value.confirmPassword) {
      console.log('Registering with:', user.value);
      submitForm(); // 调用submitForm函数
    } else {
      alert('密码不匹配，请重新输入！');
    }
  };
  
  const submitForm = () => {
    const formData = new URLSearchParams();
    formData.append('card', user.value.card);
    formData.append('username', user.value.username);
    formData.append('password', user.value.password);

    axios.post('http://localhost:8080/register', formData)
      .then(response => {
        console.log(response.data);
        if (response.data.success) {
          alert('注册成功！');
          router.push('/user-login'); // 跳转到登录页面
        } else { 
            alert('该卡号已被注册或者不存在在学生表中！');
            router.push('/user-login'); // 跳转到登录页面
        }
      })
      .catch(error => {
        console.error('There was an error!', error);
        alert('注册失败！');
      });
  };
  </script>
  
  <style scoped>
  .register-container {
    max-width: 400px;
    margin: 100px auto;
    padding: 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
  }
  
  h1 {
    color: #333;
    margin-bottom: 20px;
  }
  
  .input-group {
    margin-bottom: 15px;
  }
  
  input[type="text"],
  input[type="password"] {
    width: 100%;
    padding: 10px;
    margin-top: 5px;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-sizing: border-box; /* 使 padding 不影响宽度 */
  }
  
  button {
    width: 100%;
    padding: 10px;
    border: none;
    border-radius: 4px;
    background-color: #5cb85c; /* 绿色按钮 */
    color: white;
    font-size: 16px;
    cursor: pointer;
    margin-top: 10px;
  }
  
  button:hover {
    background-color: #4cae4c; /* 鼠标悬停时的按钮颜色 */
  }
  </style>